#include "seriallist.h"
#include <QDebug>

using namespace Moolink;

 //QList<SerialPort*> serialList;
 QMap<QString, MasterThread*> serialItems;

 static const char blankString[] = QT_TRANSLATE_NOOP("SettingsDialog", "N/A");
 QString DevName="";

SerialList::SerialList(QObject *parent)
{
//    serialItems.insert("1age", new SerialPort());
//    serialItems.insert("2like", new SerialPort());
//    serialItems.insert("4sex", new SerialPort());
}
SerialList::~SerialList()
{

}


void SerialList::setCallbackFunc(void(*func) (int devIndex,QString devName,QByteArray res,int error))
{
    m_callbackFunc = func;
}


void SerialList::transaction()
{
//    setControlsEnabled(false);
//    m_statusLabel->setText(tr("Status: Running, connected to port %1.")
//                           .arg(m_serialPortComboBox->currentText()));
//    m_thread.transaction(m_serialPortComboBox->currentText(),
//                         m_waitResponseSpinBox->value(),
//                         m_requestLineEdit->text());
}


void SerialList::showRequest(int devIndex,const QString &devName,const QByteArray &res)
{
    //qDebug()<<"SerialList:"<<s<<"\r\n";
    m_callbackFunc(devIndex,devName,res,0);
}

void SerialList::processError(int devIndex,const QString &devName,const QString &res)
{
//qDebug()<<"processError:"<<s<<"\r\n";
   m_callbackFunc(devIndex,devName,res.toLatin1(),1);
}

//void SerialList::processTimeout(int devIndex,const QString &devName,const QString &s)
//{
//qDebug()<<"processTimeout:"<<s<<"\r\n";
//   m_callbackFunc(hostIndex,hostName,res,1);
//}

QStringList SerialList::SerialRefresh(bool hand)
{

    QString description;
    QString manufacturer;
    QString serialNumber;
    QStringList hardlist;
    const auto infos = QSerialPortInfo::availablePorts();
    for (const QSerialPortInfo &info : infos) {
        QStringList list;
        description = info.description();
        manufacturer = info.manufacturer();
        serialNumber = info.serialNumber();
        list << info.portName()
             << (!description.isEmpty() ? description : blankString)
             << (!manufacturer.isEmpty() ? manufacturer : blankString)
             << (!serialNumber.isEmpty() ? serialNumber : blankString)
             << info.systemLocation()
             << (info.vendorIdentifier() ? QString::number(info.vendorIdentifier(), 16) : blankString)
             << (info.productIdentifier() ? QString::number(info.productIdentifier(), 16) : blankString);
            //qDebug()<<list;


            //如果当前获取的串口不存在则将其加入串口集合
            QMap<QString, MasterThread*>::iterator serialFinder;
            serialFinder = serialItems.find(info.portName());
            if(serialFinder == serialItems.end())
            {
                serialItems.insert(info.portName(), new MasterThread());
                serialFinder = serialItems.find(info.portName());
                connect(serialFinder.value(), &MasterThread::response2, this, &SerialList::showRequest);
                connect(serialFinder.value(), &MasterThread::error, this, &SerialList::processError);
                //connect(serialFinder.value(), &MasterThread::timeout, this, &SerialList::processTimeout);

//                QObject::connect(serialItems.constEnd().value(), &MasterThread::error, this, &SerialList::processError);
//                QObject::connect(serialItems.constEnd().value(), &MasterThread::timeout, this, &SerialList::processTimeout);
            }
            hardlist.append(info.portName());

    }

    //生成可用端口字串List，用于前端选项展示
    QStringList portList;
    QMap<QString, MasterThread*>::const_iterator i;
    for( i=serialItems.constBegin(); i!=serialItems.constEnd(); ++i)
    {
        portList.append(i.key());
        //qDebug() << i.key();// <<"        " << i.value();
        //i.value()->transaction(i.key(),QSerialPort::BaudRate(9600),QSerialPort::DataBits(8),QSerialPort::Parity(0),QSerialPort::StopBits(1),100,"hello,i'm "+i.key());
    }

    if(false==hand) return portList; else return hardlist;
}

void SerialList::writeDataToSerial(int devindex,QString devname,QString portname,int BaudRate,int DataBits,int Parity,int StopBits,int waitMSEC,QByteArray dataByte)
{
    QMap<QString, MasterThread*>::iterator serialFinder;
    serialFinder = serialItems.find(portname);
    if(serialFinder != serialItems.end())
    {
        serialFinder.value()->transaction(devindex,devname,portname,QSerialPort::BaudRate(BaudRate),QSerialPort::DataBits(DataBits),QSerialPort::Parity(Parity),QSerialPort::StopBits(StopBits),waitMSEC,dataByte);
    }
    else
    {
        //找不到这个串口,尝试刷新一下串口工具箱,如果有新的串口会自动加入
        SerialRefresh();
    }

}
